package com.kime.jwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: JiangYi
 * @Date: 2022-03-22 22:12:05
 * @Description: JWT 工具类封装
 */
public class JWTUtils {

    // 签名，不外泄
    private static final String SIGNATURE = "!Q@W3e4r%T^Y";

    /**
     * 生成 token header.payload.signature
     */
    public static String generateToken(Map<String, String> map) {

        Calendar instance = Calendar.getInstance();
        // 默认7天过期
        instance.add(Calendar.DATE, 7);
        // 创建 JWT Builder
        JWTCreator.Builder builder = JWT.create();
        // payload
        map.forEach((key, value) -> {
            builder.withClaim(key, value);
        });
        // 指定令牌的过期时间和签名
        return builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SIGNATURE));
    }

    /**
     * 验证 token 合法性
     */
    public static DecodedJWT verifyToken(String token) {
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    /**
     * 获取 token 信息
     */
    public static DecodedJWT getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

}
